package Demo_0415;

/**
 * @author:zhengyilong
 * @email:1797344574@qq.com
 * @phone:13479394730
 * @desc:   栈
 * @DateTime:2022/4/15 9:10
 **/
public class SqStackClass<E> {
    final int initcapacity = 10;
    private int capacity;
    private int top;
    private E [] data;

    public SqStackClass(){
        data =(E[]) new Object[initcapacity];
        capacity = initcapacity;
        top = -1;
    }

    //扩容
    public void updatacapacity(int newcapacity){
        E [] newdata =(E[]) new Object[newcapacity];
        for (int i = 0;i<=top;i++){
            newdata[i] = data[i];
        }
        //更新容量
        capacity = newcapacity;
        //重新指向
        data = newdata;
    }

    //判断当前栈是否为空栈
    public boolean empty(){
        return top == -1;
    }

    //将元素e压栈
    public void push(E e){
        if (top == capacity-1){//装满了
            updatacapacity((top+1) * 2);//(top+1) = capacity
        }
        top++;
        data[top] = e;
    }

    //返回当前栈顶元素，并将它出栈
    public E pop(){
        if (empty()){
            throw new IllegalArgumentException("当前栈是空栈");
        }
        E e =(E) data[top];
        top--;
        if (top+1 == capacity/4 && capacity>initcapacity){//减容
            updatacapacity(capacity/2);
        }
        return e;
    }

    //返回当前栈顶元素
    public E peek(){
        if (empty()){
            throw new IllegalArgumentException("当前栈是空栈");
        }
        return data[top];
    }

    @Override
    public String toString() {
        String answer = "";
        for (int i = 0;i<=top;i++){
            answer += data[i]+" ";
        }
        return answer;
    }
}

